//
//  LCUserAccount.swift
//  SwiftWeiBo
//
//  Created by LiCheng on 2017/2/14.
//  Copyright © 2017年 LiCheng. All rights reserved.
//

import UIKit

/// 用户信息存储的名称
fileprivate let accountFileName: NSString = "userAccount.json"

/// 用户信息
class LCUserAccount: NSObject {


    /// 访问令牌
    var access_token: String?
    /// 用户 id
    var uid: String?
    /// 令牌的生命周期
    var expires_in: TimeInterval = 0 {
        didSet {
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expires_date: Date?

    /// 昵称
    var screen_name: String?

    /// 用户头像 大图
    var avatar_large: String?


    override var description: String {

        return yy_modelDescription()
    }


    /// 重写懒加载调用方法
    override init() {

        super.init()

        // 从磁盘中加载保存的文件 -> 字典
        // 1> 加载磁盘文件到二进制数据， 如果失败直接返回
        guard let path = accountFileName.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]

            else {
                return
        }

        // 2> 设置属性
        yy_modelSet(with: dict ?? [:])

        // 3> 判断 token 是否过期
        // 测试日期
        // expires_date = Date(timeIntervalSinceNow: -3600 * 24)

        if expires_date?.compare(Date()) != .orderedDescending {

            //    - orderedDescending 降序(过期时间和当前时间比较)
            print("token 过期")

            // 1. 情况 token
            access_token = nil
            uid = nil

            // 2. 删除账户文件
            _ = try? FileManager.default.removeItem(atPath:path)
        }
        print("账户正常")
    }


    /// 数据存储
    func saveAccount() {

        // 1. 字典转模型
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        //    -> 删除 expires_in
        dict.removeValue(forKey: "expires_in")

        // 2. 字典序列化 data
        //    -> filePath 路径
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
             let filePath = accountFileName.cz_appendDocumentDir() else {

                return
        }

        // 3. 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)


        print("保存成功\(filePath)")
    }
}







